<template>
  <div class="g-page-container">
    <PageHeader title="线索创建" />
    <div class="g-content-container">
      <SearchForm ref="search-form" @search="getList(1)" />
      <ButtonGroup :options="buttons" @click="handleButtonClick" />
      <TableList
        :scroll="{ x: '100%', y: 'calc(100vh - 400px)' }"
        :pagination="paginationMixin"
        :loading="loading"
        :data-source="dataSource"
        :row-selection="rowSelectionMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>
    <component
      :is="currentComponent"
      :visible.sync="visibleDrawer"
      :current-node="currentNode"
      :detail="detail"
      :plan-id="planId"
      :process-id="processId"
      :click-info="clickInfo"
      @number-click="clickInfo"
      @fresh="getList"
    />
    <DialogTransferClue
      :visible.sync="visibleModal"
      :plan-id="planId"
      :selecteds="selectedInfos"
      number="线索编号"
      @fresh="getList"
    />
    <DrawerDeatil
      :visible.sync="visibleDetail"
      :detail="detail"
      :plan-id="planId"
      :process-id="processId"
      :click-info="clickInfo"
    />
  </div>
</template>

<script>
import SearchForm from './components/SearchForm.vue';
import ButtonGroup from '@/components/button/ButtonGroup.vue';
import TableList from './components/TableList.vue';
import mixinTable from '@/mixins/mixin-table.js';
import DialogTransferClue from '@/components/dialog/DialogTransferClue.vue';
import { postClueList, getClueDetails, postDeleteClue } from '@/api/clue.js';
import { CLUE_NODE } from '@/constants/index';

import DrawerClueAdd from './components/DrawerClueAdd.vue';
import DrawerClueEdit from './components/DrawerClueEdit.vue';
import DrawerDeparmentAudit from './components/DrawerDeparmentAudit.vue';
import DrawerKAPMAudit from './components/DrawerKAPMAudit.vue';
import DrawerSalerAudit from './components/DrawerSalerAudit.vue';
import DrawerEnd from './components/DrawerEnd.vue';
import DrawerDeatil from './components/DrawerDetail.vue';
export default {
  components: {
    SearchForm,
    ButtonGroup,
    TableList,
    DrawerClueAdd,
    DrawerClueEdit,
    DrawerDeparmentAudit,
    DrawerKAPMAudit,
    DrawerSalerAudit,
    DrawerEnd,
    DrawerDeatil,
    DialogTransferClue,
  },
  mixins: [mixinTable],
  data() {
    return {
      visibleDrawer: false,
      visibleModal: false,
      visibleDetail: false,
      currentComponent: 'DrawerClueAdd',
      detail: {},
      planId: undefined,
      asc: true,
      processId: undefined,
      currentNode: CLUE_NODE[1],
      uid: this.$store.state.user.uid,
      columnKey: '',
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.query?.leadsNo) {
        vm.handleNumberClick(to.query);
      } else if (to.query?.type === 'routerAdd') {
        vm.addCallback(to.query);
      }
    });
  },
  computed: {
    buttons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          type: 'primary',
          label: '新增线索',
          authKey: 'clue-create-button-add',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
          authKey: 'clue-create-button-delete',
          disabled,
        },
        {
          key: 'retweet',
          label: '转他人处理',
          icon: 'retweet',
          authKey: 'clue-create-button-retweet',
          disabled,
        },
      ];
    },
    searchForm() {
      return this.$refs['search-form']?.form || {};
    },
  },
  watch: {
    visibleModal: {
      handler(val) {
        if (!val) {
          this.rowSelectionMixin.selectedRowKeys = [];
        }
      },
    },
  },
  created() {
    this.getList();
  },
  methods: {
    getSearchForm() {
      const form = this.$refs['search-form']?.form || {};
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
      };
      return {
        ...form,
        ...page,
        snapshootType: 'create',
        bizType: '1',
        bizModule: 'leads',
        status: '1',
      };
    },
    // 获取列表信息
    async getList(val) {
      if (val) {
        this.paginationMixin.current = 1;
      }
      const form = this.getSearchForm();
      this.loading = true;
      const result = await postClueList(form).finally(
        () => (this.loading = false)
      );
      this.dataSource = result.data.data?.records;
      this.paginationMixin.total = result.data.data?.total;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]({});
    },
    // 新增按钮
    addCallback(query) {
      console.log(query, '-------');
      const val = query || {};
      if (val.customerName) {
        this.detail = {
          customerCode: val.customerNo, // 客户编码
          customerName: val.customerName, // 客户名称
          customerShortName: val.name, // 客户简称
          type: val.type,
        };
      } else {
        this.detail = {};
      }
      this.currentComponent = 'DrawerClueAdd';
      this.currentNode = CLUE_NODE[1];
      this.planId = undefined;
      this.visibleDrawer = true;
    },
    // 删除按钮
    async deleteCallback() {
      const selectedRowKeys = this.rowSelectionMixin.selectedRowKeys || [];
      const checkedRows = this.dataSource.reduce((pre, cur) => {
        if (selectedRowKeys.includes(cur.id)) {
          pre.push(cur);
        }
        return pre;
      }, []);
      const ids = checkedRows
        .filter(
          item =>
            (item.createUserId === this.uid && item.currStatus === '1') ||
            (item.createUserId === this.uid && item.currStatus === '5')
        )
        .map(item => item.id);
      if (!ids.length) {
        this.$message.info(
          `仅可删除本人创建的草稿状态与已驳回的数据，共 ${ids.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可删除草稿状态与已驳回状态的数据，共 ${ids.length} 条，是否确认？`
        );

        await postDeleteClue(ids);
        this.$message.success('删除成功');
        this.rowSelectionMixin.selectedRowKeys = [];
        this.getList();
      } catch (error) {
        //
        // console.log('error: ', error);
      }
    },
    // 转他人处理
    async retweetCallback() {
      const selectedInfos = this.rowSelectionMixin.selectedRows
        .filter(item => item.currStatus === '2')
        .map((item, i) => {
          return {
            serialNumber: item.leadsNo,
            currentUserId: item.handleUserId,
            planId: item.id,
          };
        });
      if (!selectedInfos.length) {
        this.$message.info(
          `仅可转审批中的数据，现有 ${selectedInfos.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可转审批中的数据，共 ${selectedInfos.length} 条，是否确认？`
        );
        this.visibleModal = true;
        this.selectedInfos = selectedInfos;
      } catch (error) {
        // console.log('error: ', error);
      }
    },
    // 线索编号弹框
    async handleNumberClick(record) {
      if (record.path) {
        // let currentNode = CLUE_NODE[Number(record.nodeCode)];
        if (!record.nodeCode) {
          // this.$message.error('非有效节点，无法进入！');
          // return;
          this.currentComponent = 'DrawerEnd';
        } else {
          this.currentNode = CLUE_NODE[Number(record.nodeCode)];
          this.currentComponent = `Drawer${this.currentNode.key}`;
        }
      } else {
        if (record.isCurrentProcessor) {
          this.currentNode = CLUE_NODE[Number(record.nodeCode)] || CLUE_NODE[1];
          this.currentComponent = `Drawer${this.currentNode.key}`;
        } else {
          this.currentComponent = 'DrawerEnd';
        }
      }
      const res = await getClueDetails(record.leadsNo);
      this.detail = res.data.data;
      this.planId = this.detail.id;
      this.processId = this.detail.processId;
      this.visibleDrawer = true;
    },
    // 分页
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.getList();
    },
    clickInfo(val) {
      this.detail = val;
      this.planId = val.id;
      this.processId = val.processId;
      this.visibleDetail = true;
    },
  },
};
</script>

<style lang="less" scoped>
.table-container {
  padding: 10px 20px;
  height: calc(100vh - 160px);
  box-sizing: border-box;
}
</style>
